package edu.whu.powersoap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.lbsapi.auth.LBSAuthManagerListener;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.navisdk.BNaviEngineManager.NaviEngineInitListener;

import edu.whu.powersoap.R;

public class MainActivity extends Activity {

	public static String user;
	private static final String TAG = "MainActivity";
	private LayoutInflater mLayoutInflater;

	/**
	 * 构造广播监听类，监听 SDK key 验证以及网络异常广播
	 */
	public class SDKReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			String s = intent.getAction();
			Log.i(TAG, "----action: " + s);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_menu);

		BaiduNaviManager.getInstance().initEngine(this, getSdcardDir(),
				mNaviEngineInitListener, new LBSAuthManagerListener() {
					@Override
					public void onAuthResult(int status, String msg) {
						String str = null;
						if (0 == status) {
							str = "key校验成功!";
						} else {
							str = "key校验失败, " + msg;
						}
						Log.i(TAG, str);
						Toast.makeText(MainActivity.this, str,
								Toast.LENGTH_LONG).show();
					}
		});
		
		mLayoutInflater = LayoutInflater.from(this);
		Button btn;
		btn = (Button) findViewById(R.id.log_in);
		btn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				//LayoutInflater factory = LayoutInflater.from(this);
				
				final View textEntryView = mLayoutInflater.inflate(R.layout.log_dialog, null);
				Dialog dialog = new AlertDialog.Builder(MainActivity.this)
						.setMessage("Input your usrname and password")
						.setTitle("Log in").setView(textEntryView)
						.setPositiveButton("确认", 
						new DialogInterface.OnClickListener() {
		
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							EditText text;
							text = (EditText) textEntryView.findViewById(R.id.username_edit);
							String username = text.getText().toString();							
							text = (EditText) textEntryView.findViewById(R.id.password_edit);
							String password = text.getText().toString();
								
							if (verifyUser(username, password)){
								
								MainActivity.this.finish();
								startActivity(new Intent(MainActivity.this, MenuActivity.class));
								user = username;
								
							}else {
								
								final Dialog dialog1 = new AlertDialog.Builder(MainActivity.this)
								.setMessage("用户名密码错误，请重新登录")
								.setTitle("提示")
								.setPositiveButton("确认",
								new DialogInterface.OnClickListener() {		
								@Override
								public void onClick(DialogInterface dialog1, int which) 
								{
									dialog1.dismiss();
								}
								}).create();
									
								dialog1.show();
							 }
												
							}
						}).create();
				dialog.show();
			}
		});
		
		btn = (Button) findViewById(R.id.log_up);
		if (btn != null) {
			btn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					final View userAddView = mLayoutInflater.inflate(
							R.layout.log_up, null);

					Dialog userAddDialog = new AlertDialog.Builder(
							MainActivity.this)
							.setTitle("添加用户")
							.setView(userAddView)
							.setPositiveButton("添加",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {

											EditText input;
											input = (EditText) userAddView
													.findViewById(R.id.username_edit);
											String username = input.getText()
													.toString();
											input = (EditText) userAddView
													.findViewById(R.id.password_edit);
											String password = input.getText()
													.toString();
											input = (EditText) userAddView
													.findViewById(R.id.password_confirm_edit);
											String password_confirm = input
													.getText().toString();
											CheckBox isAdmin = (CheckBox) userAddView
													.findViewById(R.id.is_admin);
											long flag = 0;
											if (isAdmin.isChecked())
												flag |= UserInfo.FLAG_ADMIN;

											if ((password == null) || !password.equals(password_confirm)) 
											{
												showHintDialog("提示",
														"创建用户失败, 密码不一致!");
												return;
											}

											UserProvider.addUser(MainActivity.this, username, password_confirm, flag);
											showHintDialog("提示", "创建用户成功");
										}
									}).setNegativeButton("取消",new DialogInterface.OnClickListener() 
									{
										public void onClick(DialogInterface dialog, int whichButton) 
										{
											dialog.dismiss();
										}
									}).create();

					userAddDialog.show();

				}

			});
			
			btn = (Button) findViewById(R.id.user_management);
			
		}
	}
		 private boolean verifyUser(String username, String password) {
		 UserInfo user = UserProvider.getUserFromName(MainActivity.this, username);
		 Log.d(TAG, "verify user=" + user);
		
		 if (user == null) {
		 if (username.equals("admin")) {
			 UserProvider.addUser(MainActivity.this, username, password, UserInfo.FLAG_ADMIN);
			 return true;
		 }
		
		 return false;
		 }
		
		 boolean result = (password != null)
		 && password.equals(user.getPassword());
		 GlobalApplication app = (GlobalApplication) getApplication();
		 if (result) {
		
		 app.setLoginUser(user);
		 } else
		 app.setLoginUser(null);
		
		 return result;
		 }
	
		private String getSdcardDir() {
			if (Environment.getExternalStorageState().equalsIgnoreCase(
					Environment.MEDIA_MOUNTED)) {
				return Environment.getExternalStorageDirectory().toString();
			}
			return null;
		}
	
		private NaviEngineInitListener mNaviEngineInitListener = new NaviEngineInitListener() {
			public void engineInitSuccess() {
			}
	
			public void engineInitStart() {
			}
	
			public void engineInitFail() {
			}
		};
		
		private void showHintDialog(String title, String msg) {
			new AlertDialog.Builder(MainActivity.this).setTitle(title)
					.setMessage(msg)
					.setPositiveButton("确认", new DialogInterface.OnClickListener() {
	
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					}).show();
		}
	}

